package main

import (
	"flag"
	"fmt"
	"net/http"

	"gitee.com/thubcc/blockchain/accounts"
	"gitee.com/thubcc/fmstream/p2p"
	"gitee.com/thubcc/rtlmmap/web"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/common/log"
)

var (
	argTopic    = flag.String("topic", "44c7429f", "topic in hexadecimal format (e.g. 70a4beef)")
	argPass     = flag.String("password", "123456", "message's encryption password")
	argDataDir  = flag.String("dir", ".ethereum/chain", "ethereum data dir")
	argKeyPass  = flag.String("p", "931", "message's encryption password")
	argPrefix   = flag.String("u", "a4a8", "address prefix")
	argMax      = flag.Int64("m", 1000000, "Max search")
	argAddr     = flag.String("addr", "0x69B47aD51691905D4ae1B3b61B27164C1776D08B", "contract address")
	argListen   = flag.Int("listen", 8081, "web listen port")
	enodeString = flag.String("n", p2p.DefaultNode, "enode")
)
var (
	client *p2p.P2PFMer
)

func systemStart() {
	keyConfig := accounts.NewConfig(*argDataDir, true, *argMax)
	prk, err := keyConfig.FindKey(*argPrefix, *argKeyPass)
	if err != nil {
		log.Error(err)
		return
	}
	var p2pconfig = &p2p.Config{*enodeString, prk}

	client, err = p2p.NewP2PFMer(p2pconfig, web.GetOtoContext(), p2p.NilName("raw"))
	if err != nil {
		log.Error(err)
		return
	}
	client.Run(*argTopic, *argPass)
}

func systemStop() {
	client.Close()
}

func Init() (r *gin.Engine, err error) {
	r = gin.Default()
	r.GET("/stop", func(c *gin.Context) {
		systemStop()
		c.String(http.StatusOK, "client stop")
	})
	r.GET("/start", func(c *gin.Context) {
		systemStart()
		c.String(http.StatusOK, "client start")
	})
	return
}

func main() {
	flag.Parse()
	r, err := Init()
	if err == nil {
		r.Run(fmt.Sprintf(":%d", *argListen))
	}
}
